package com.mediacloud.app.newsmodule.fragment.video.vod

import android.content.Intent
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.widget.TextView
import androidx.annotation.RequiresApi
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.util.GsonUtils
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.mediacloud.app.assembly.util.isFastClick
import com.mediacloud.app.assembly.util.jsonToArrayList
import com.mediacloud.app.fbnavsk.navPaddingTopMatch
import com.mediacloud.app.model.interfaces.DataInvokeCallBack
import com.mediacloud.app.model.news.ArticleItem
import com.mediacloud.app.model.news.ArticleListData
import com.mediacloud.app.model.news.BaseMessageReciver
import com.mediacloud.app.model.news.CatalogItem
import com.mediacloud.app.model.utils.ViewUtils
import com.mediacloud.app.model.view.floatwin.FloatButtonGroup
import com.mediacloud.app.nav2.fragment.HqyNavFragment
import com.mediacloud.app.newsmodule.R
import com.mediacloud.app.newsmodule.activity.microlive.BaseRecyclerAdapter
import com.mediacloud.app.newsmodule.fragment.baoliao.api.SpiderCmsApi
import com.mediacloud.app.newsmodule.utils.NewsItemClickUtils
import com.mediacloud.app.newsmodule.utils.NewsListDataInvoker
import com.mediacloud.app.reslib.util.ModuleReferenceConfig
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener
import com.utils.DeviceUtils
import com.utils.RxUtils
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.fragment_movie_series.*
import org.jetbrains.anko.backgroundResource
import org.jetbrains.anko.textColor
import org.json.JSONArray
import org.json.JSONObject

/**
 * @author Heaven Created on 2022/6/28
 */
class MovieSeriesFragment : HqyNavFragment(), BaseRecyclerAdapter.ItemClickListener {

    var dataInvoker: NewsListDataInvoker? = null
    var dataCallback: BaseDataInvokeCallBack<out BaseMessageReciver?>? = null

    var orderField: String? = null
    val LOGIN = 1
    val REFRESH = 2
    var Mode = REFRESH

    var catalogItem: CatalogItem? = null
    var catalogID: String? = null
    var pageIndex = 1
    var perPageSize = 20
    private var cateId: String? = ""
    lateinit var movieGridAdapter: MovieSeriesListAdapter

    lateinit var countryAdapter: CategoryAdapter

    lateinit var childCategoryAdapter: ChildCategoryAdapter

    //    private var chooseType: Boolean = false
    private var map: MutableMap<Int, MutableList<MovieCategoryDataBean>> = mutableMapOf()
    private var categoryMap: MutableMap<Int, Int> = mutableMapOf()

    override fun getLayoutResID(): Int {
        return R.layout.fragment_movie_series
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        this.navPaddingTopMatch()
    }

    fun setOrderField(positon: Int, isGetData: Boolean) {
        if (positon == 0) {
            tv_all?.isSelected = true
            tv_publishDate?.isSelected = false
            tv_hitCount?.isSelected = false
            orderField = null
        } else if (positon == 1) {
            tv_all?.isSelected = false
            tv_publishDate?.isSelected = true
            tv_hitCount?.isSelected = false
            orderField = "publishDate"
        } else if (positon == 2) {
            tv_all?.isSelected = false
            tv_publishDate?.isSelected = false
            tv_hitCount?.isSelected = true
            orderField = "hitCount"
        }

        if (isGetData) {
            refresh()
        }
    }

    override fun initView() {
        if (DeviceUtils.isCus(context)) {
            ll_tab?.visibility = View.VISIBLE
            setOrderField(0, false)
            RxUtils.rxClick(tv_all) {
                setOrderField(0, true)
            }
            RxUtils.rxClick(tv_publishDate) {
                setOrderField(1, true)
            }
            RxUtils.rxClick(tv_hitCount) {
                setOrderField(2, true)
            }
        } else {
            ll_tab?.visibility = View.GONE
        }

        layout_search.setOnClickListener {
            if (isFastClick()) {
                val intent = Intent()
                intent.setClassName(requireContext(), ModuleReferenceConfig.SearchActivity)
                startActivity(intent)
            }

        }
        refreshLayout.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onRefresh(refreshLayout: RefreshLayout) {
                refresh()
            }

            override fun onLoadMore(refreshLayout: RefreshLayout) {
                loadMore()
            }
        })
        val layoutManager = GridLayoutManager(activity, 3)
        layoutManager.orientation = LinearLayoutManager.VERTICAL
        recyclerView.layoutManager = layoutManager
        recyclerView.setBackgroundColor(Color.WHITE)
        movieGridAdapter = MovieSeriesListAdapter(activity)
        movieGridAdapter.setItemClickListener(this)
        recyclerView.adapter = movieGridAdapter
        loadingView = mRootView.findViewById(R.id.mLoadingView)
        loadingImage = loadingView.findViewById(R.id.image_loading)
        retryTips = loadingView.findViewById(R.id.retryTips)
        if (retryTips != null) {
            retryTips.setOnClickListener {
                showStateView(TYPE_LOADING, false)
                refresh()
            }
        }

        rcyMainType.layoutManager =
            LinearLayoutManager(requireContext(), RecyclerView.HORIZONTAL, false)
        countryAdapter = CategoryAdapter(R.layout.item_series_category)
        rcyMainType.adapter = countryAdapter

        countryAdapter?.setOnItemClickListener { adapter, view, position ->
            countryAdapter.choosePosition = position
            countryAdapter.notifyDataSetChanged()
            if (!map.isNullOrEmpty() && !countryAdapter.data.isNullOrEmpty() && countryAdapter.data.size >= position && childCategoryAdapter != null) {
                categoryMap.clear()
                categoryMap[1] = countryAdapter.data[position].id
                map[countryAdapter.data[position].id]?.forEach {
                    it.meta?.forEachIndexed { index, movieCategoryBean ->
                        movieCategoryBean.selected = index == 0
                    }
                }
                childCategoryAdapter.setNewData(map[countryAdapter.data[position].id])
                childCategoryAdapter.notifyDataSetChanged()
                getDramaData()
            }
        }

        rcyChild.layoutManager = LinearLayoutManager(requireContext())
        childCategoryAdapter = ChildCategoryAdapter()
        rcyChild.adapter = childCategoryAdapter

        load()
        //   getCategoryData()
    }

    override fun initArgs() {
        super.initArgs()
        if (fragmentArguments != null) {
            saveInstanceArguments = fragmentArguments
            catalogID = saveInstanceArguments?.getString("id")
            catalogItem = saveInstanceArguments?.getParcelable("catalog")
        } else if (saveInstanceArguments != null) {
            catalogID = saveInstanceArguments?.getString("id")
            catalogItem = saveInstanceArguments?.getParcelable("catalog")
        }
        val navigateArgs = if (catalogItem != null && catalogItem?.navigate != null) {
            catalogItem?.navigate
        } else {
            super.navigate
        }
        navigate = navigateArgs
        initCallBackInstance()
        initDataInvoker()
    }

    override fun onResume() {
        super.onResume()
        refresh()
    }

    private fun getDramaData() {
        loadingView.setBackgroundColor(Color.TRANSPARENT)
        showStateView(TYPE_LOADING, false)
        var ids: StringBuffer = StringBuffer()
        for (key in categoryMap.keys) {
            categoryMap[key]?.let {
                ids.append(",${categoryMap[key]}")
            }
            Log.e("getDramaData", "key= " + key + " and value= " + categoryMap[key])
        }
        val map = mutableMapOf<String, Any>()
        map["pageNumber"] = pageIndex
        map["pageSize"] = perPageSize
        if (!TextUtils.isEmpty(orderField)) {
            map["orderField"] = orderField!!
            map["orderDirection"] = "DESC"
        }
        if (!cateId.isNullOrEmpty()) {
            map["catalogIds"] = cateId!!
        }
        if (ids.startsWith(",")) {
            map["albumTypeIds"] = ids.substring(1, ids.length)
        }
        SpiderCmsApi.getSpiderCmsApiJson(requireContext())
            .findSeriesVideoAlbumPage(getString(R.string.tenantid), map)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Observer<JSONObject> {
                override fun onSubscribe(d: Disposable) {
                    compositeDisposable.add(d)
                }

                override fun onNext(t: JSONObject) {
                    if (activity == null || requireActivity().isFinishing || requireActivity().isDestroyed) {
                        return
                    }
                    refreshLayout.finishRefresh()
                    refreshLayout.finishLoadMore()
                    closeStateView()
                    val success = t.optBoolean("success")
                    if (success) {
                        val json = t.optJSONObject("data")
                        if (json != null) {
                            val hasNextPage = json.optBoolean("hasNextPage")
                            if (!hasNextPage) {
                                refreshLayout.setNoMoreData(true)
                            }
                            if (pageIndex == 1) {
                                movieGridAdapter.data.clear()
                            }
                            val meta = json.optJSONArray("pageRecords")
                            if (meta != null && meta.length() > 0) {
                                val list = arrayListOf<ArticleItem>()
                                for (i in 0 until meta.length()) {
                                    val item = meta.optJSONObject(i)
                                    val articleItem = ArticleItem()
                                    articleItem.id = item.optLong("articleId")
                                    articleItem.logo = item.optString("logo")
                                    articleItem.title = item.optString("title")
                                    articleItem.type = item.optString("type").toInt()
                                    articleItem.url = item.optString("url")
                                    val logoFlag = item.optJSONObject("logoFlag")
                                    logoFlag?.let{
                                        articleItem.lable = it.optString("title")
                                    }
//                                    if (!item.optString("appCustom").isNullOrEmpty()) {
//                                        val jsonObject = JSONObject(item.optString("appCustom"))
//                                        val movie = jsonObject.optJSONObject("movie")
//                                        if (movie?.optString("logoFlag") != null) {
//                                            val array = JSONArray(movie?.optString("logoFlag"))
//                                            array?.let {
//                                                val logoFlagBean = jsonToArrayList(
//                                                    it.toString(),
//                                                    LogoFlagBean::class.java
//                                                )
//                                                if (!logoFlagBean.isNullOrEmpty()) {
//                                                    articleItem.lable = logoFlagBean[0].logoFlag
//                                                }
//                                            }
//
//                                        }
//
//                                    }

                                    articleItem.appCustomParams =
                                        item.optJSONObject("appCustomParams")
                                            ?.toString()
                                            ?: ""
                                    articleItem.author = item.optString("authorAvatar")
                                    articleItem.Author = item.optString("authorNickName")
                                    articleItem.favorCount_format = item.optInt("hitCount")
                                        .toString()
                                    articleItem.commentCount = item.optLong("commentCount")
                                    articleItem.commentCount_format = item.optString("commentCount")
                                    articleItem.supportCount = item.optLong("favorCount")
                                    articleItem.catalogId = item.optInt("catalogId")
                                    list.add(articleItem)
                                }
                                empty_content.visibility = View.GONE
                                recyclerView.visibility = View.VISIBLE
                                movieGridAdapter.data.addAll(list)
                            } else {
                                movieGridAdapter.data.addAll(emptyList())
                                empty_content.visibility = View.VISIBLE
                                recyclerView.visibility = View.GONE
                            }
                        } else {
                            movieGridAdapter.data.addAll(emptyList())
                            empty_content.visibility = View.VISIBLE
                            recyclerView.visibility = View.GONE
                        }
                    } else {
                        movieGridAdapter.data.addAll(emptyList())
                        empty_content.visibility = View.VISIBLE
                        recyclerView.visibility = View.GONE
                    }
                    movieGridAdapter.notifyDataSetChanged()
                }

                override fun onError(e: Throwable) {
                    if (activity == null || requireActivity().isFinishing || requireActivity().isDestroyed) {
                        return
                    }
                    Log.e(TAG, "${e.message}")
                    refreshLayout.finishRefresh()
                    refreshLayout.finishLoadMore()
                    closeStateView()
                    empty_content.visibility = View.VISIBLE
                    recyclerView.visibility = View.GONE
                }

                override fun onComplete() {}
            })
    }

    private fun refresh() {
        pageIndex = 1
        if (countryAdapter != null && countryAdapter.data.isNullOrEmpty()) {
            load()
        } else {
            getDramaData()
        }
    }

    private fun loadMore() {
        pageIndex++
        getDramaData()
    }

    private fun load() {
        Mode = REFRESH
        dataInvoker?.getContentList(catalogID, pageIndex, perPageSize, null)
    }


    private fun initDataInvoker() {
        dataInvoker = NewsListDataInvoker(dataCallback)
    }


    protected fun getDataInvokeCallBackClass(): Class<out BaseDataInvokeCallBack<out BaseMessageReciver?>?> {
        return BaseNewsDataInvokeCallBack::class.java
    }


    private fun initCallBackInstance() {
//        val classRef: Class<*> = getDataInvokeCallBackClass()
        try {
//            dataCallback = classRef.constructors[0].newInstance(this) as BaseDataInvokeCallBack<out BaseMessageReciver?>
            dataCallback = BaseNewsDataInvokeCallBack()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun onItemClick(index: Int, isFromAdaptor: Boolean, adapter: BaseRecyclerAdapter<*>?) {
        val item = movieGridAdapter.getItem(index)
        val type = item.getType()
        NewsItemClickUtils.OpenItemNewsHandle(context, type, item, catalogItem)
//        TikTokActivity.startActivity(requireContext(), recyclerAdapter.data as ArrayList<ArticleItem>, index, catalogItem.catid, pageIndex, 0)

    }


    abstract inner class BaseDataInvokeCallBack<T> : DataInvokeCallBack<T> {
        override fun fault(`object`: Any) {
            if (activity == null || requireActivity().isFinishing || requireActivity().isDestroyed) {
                return
            }
            refreshLayout.finishRefresh(false)
            refreshLayout.finishLoadMore()
            //            refreshLayout.setRefreshing(false);
            pageIndex--
            if (`object` != null && movieGridAdapter != null && (movieGridAdapter.data == null
                        || movieGridAdapter.data.size == 0)
            ) {
                showStateView(TYPE_NET_NOT_GIVE_FORCE, false)
            } else if (movieGridAdapter != null && (movieGridAdapter.data == null
                        || movieGridAdapter.data.size == 0)
            ) {
                showStateView(TYPE_NO_CONTENT, false)
            } else closeStateView()
            ViewUtils.showToast(activity, "获取数据失败") //,Snackbar.LENGTH_SHORT).show();
        }
    }

    inner class BaseNewsDataInvokeCallBack : BaseDataInvokeCallBack<ArticleListData?>() {
        override fun success(result: ArticleListData?) {
            if (activity == null || requireActivity().isFinishing || requireActivity().isDestroyed) {
                return
            }
            if (pageIndex == 1) refreshLayout.finishRefresh()
            result?.let {
                if (!result.more) refreshLayout.finishLoadMoreWithNoMoreData() else refreshLayout.finishLoadMore()
                //必须 的
                val floatData = result.orginData.optJSONObject("data")
                if (pageIndex == 1) {
                    if (FloatButtonGroup.haveFloatField(floatData)) {
                        initFloatWin(floatData)
                    } else {
                        hideFloatWin()
                    }
                }

                if (floatData != null) {
                    closeStateView()
                    val mData: MovieCategoryDataBean =
                        GsonUtils.fromJson(floatData.toString(), MovieCategoryDataBean::class.java)
                    cateId = mData.navigate?.catid
                    if (mData != null && !mData.meta.isNullOrEmpty()) {
                        empty_content.visibility = View.GONE
                        recyclerView.visibility = View.VISIBLE
                        val data = mData.meta

                        data?.forEach {
                            val parentList: MutableList<MovieCategoryDataBean> = mutableListOf()
                            if (!it.childAlbumTypes.isNullOrEmpty()) {
                                it.childAlbumTypes?.forEach { item ->
                                    val movieCategoryDataBean = MovieCategoryDataBean()
                                    movieCategoryDataBean.meta = mutableListOf()
                                    if (!item.childAlbumTypes.isNullOrEmpty()) {
                                        item.selected = true
                                        movieCategoryDataBean.meta?.add(item)
                                        item.childAlbumTypes?.forEach { child ->
                                            movieCategoryDataBean.meta?.add(child)
                                        }
                                    }
                                    parentList.add(movieCategoryDataBean)


                                }

                            }
                            map[it.id] = parentList
                        }
                        if (!map.isNullOrEmpty() && !data.isNullOrEmpty()) {
                            if (mData.content_type_selected.isNullOrEmpty()) {
                                countryAdapter.setNewData(data)
                                map[data[0].id]?.get(0)?.meta?.get(0)?.selected = true
                                childCategoryAdapter.setNewData(map[data[0].id])
                                categoryMap[1] = data[0].id
                            } else {
                                var index: Int = -1
                                run outsize@{
                                    mData.content_type_selected?.forEach { selected ->
                                        index = data.indexOfFirst { it1 -> it1.id == selected.id }
                                        return@outsize
                                    }
                                }
                                if (index != -1) {
                                    categoryMap[1] = data[index].id
                                    val value = map[data[index].id]
                                    value?.forEachIndexed { index, movieCategoryDataBean ->
                                        movieCategoryDataBean?.meta?.forEachIndexed { i, movieCategoryBean ->
                                            run outsize@{
                                                mData.content_type_selected?.forEach { selected ->
                                                    if (movieCategoryBean.id == selected.id) {
                                                        movieCategoryBean.selected = true
                                                        if (i != 0) {
                                                            categoryMap[index + 2] =
                                                                movieCategoryBean.id
                                                        }
                                                        return@outsize
                                                    } else {
                                                        movieCategoryBean.selected = false
                                                    }
                                                }
                                            }


                                        }
                                    }
                                    map[data[index].id]?.forEachIndexed { index, movieCategoryDataBean ->
                                        val indexOf =
                                            movieCategoryDataBean.meta?.indexOfLast { it2 -> it2.selected == true }
                                        if (indexOf == -1) {
                                            movieCategoryDataBean.meta?.get(0)?.selected = true
                                        } else if (indexOf != 0) {
                                            movieCategoryDataBean.meta?.get(0)?.selected = false
                                        }
                                    }
                                    countryAdapter.choosePosition = index
                                    childCategoryAdapter.setNewData(map[data[index].id])

                                } else {
                                    categoryMap[1] = data[0].id
                                    map[data[0].id]?.get(0)?.meta?.get(0)?.selected = true
                                    childCategoryAdapter.setNewData(map[data[0].id])

                                }
                                countryAdapter.setNewData(data)

                            }
                            getDramaData()
                        }
                    } else {
                        empty_content.visibility = View.VISIBLE
                        recyclerView.visibility = View.GONE
                    }
                } else {
                    empty_content.visibility = View.VISIBLE
                    recyclerView.visibility = View.GONE
                }

            }
        }
    }

    inner class CategoryAdapter(layoutRes: Int) :
        BaseQuickAdapter<MovieCategoryBean, BaseViewHolder>(layoutRes) {

        var choosePosition: Int = 0

        override fun convert(helper: BaseViewHolder, item: MovieCategoryBean?) {
            val content: TextView = helper.getView(R.id.content)
            item?.let {
                content.text = "${it.name}"
                if (helper.adapterPosition == choosePosition) {
                    content.backgroundResource = R.drawable.shape_d43d3d__rectangle
                    content.textColor = Color.parseColor("#ffffff")
                } else {
                    content.backgroundResource = 0
                    content.textColor = Color.parseColor("#222222")
                }
            }

        }
    }


    inner class ChildCategoryAdapter :
        BaseQuickAdapter<MovieCategoryDataBean, BaseViewHolder>(R.layout.item_movie_child_category) {

        override fun convert(helper: BaseViewHolder, item: MovieCategoryDataBean?) {

            val rcyChildCate = helper.getView<RecyclerView>(R.id.rcyChildCate)
            val childCategoryAdapter = MCategoryAdapter(R.layout.category_item)
            rcyChildCate.adapter = childCategoryAdapter
            rcyChildCate.layoutManager =
                LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)

            childCategoryAdapter.setNewData(item?.meta)
            childCategoryAdapter.setOnItemClickListener { adapter, view, position ->
                childCategoryAdapter.data.forEach {
                    it.selected = it.id == childCategoryAdapter.data[position].id
                }
                childCategoryAdapter.notifyDataSetChanged()
                if (position == 0 && categoryMap.containsKey(helper.absoluteAdapterPosition + 2)) {
                    categoryMap.remove(helper.absoluteAdapterPosition + 2)
                } else if (!childCategoryAdapter.data.isNullOrEmpty() && childCategoryAdapter.data.size >= position) {
                    Log.e(
                        "getDramaData",
                        "helper= " + helper.absoluteAdapterPosition + "id" + childCategoryAdapter.data[position].id
                    )
                    categoryMap.put(
                        helper.absoluteAdapterPosition + 2,
                        childCategoryAdapter.data[position].id
                    )

                }
                Log.e("getDramaData", "categoryMap" + categoryMap.size)
                getDramaData()
            }

        }

    }

    inner class MCategoryAdapter(layoutRes: Int) :
        BaseQuickAdapter<MovieCategoryBean, BaseViewHolder>(layoutRes) {

        override fun convert(helper: BaseViewHolder, item: MovieCategoryBean?) {
            val content: TextView = helper.getView(R.id.content)
            item?.let {
                content.text = "${it.name}"
                if (item.selected == true) {
                    content.backgroundResource = R.drawable.shape_d43d3d__rectangle
                    content.textColor = Color.parseColor("#ffffff")
                } else {
                    content.backgroundResource = 0
                    content.textColor = Color.parseColor("#222222")
                }
            }

        }
    }

    override fun onDestroy() {
        super.onDestroy()
        compositeDisposable.dispose()
        if (dataInvoker != null) {
            dataInvoker!!.destory()
        }
    }
}